package com.guaju.yueshangLife.global;

import android.app.Application;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.guaju.yueshangLife.activity.MainActivity;
import com.guaju.yueshangLife.base.GoodsDetail;
import com.guaju.yueshangLife.imageloader.FrescoImgLoader;
import com.guaju.yueshangLife.imageloader.GlideImgLoader;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBaseConfig;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMGroupEventListener;
import com.tencent.imsdk.TIMGroupTipsElem;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMRefreshListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.session.SessionWrapper;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;

/**
 * Created by guaju on 2018/9/10.
 */

public class BaseApplication extends Application {
    static BaseApplication app;
    private String tag = "guajujerry";
    static LiteOrm liteOrm;
    private MainActivity mainActivity;
    private String appID = "wx4ebbe18fb43faea1";
    private IWXAPI wxapi;
    private boolean retryable = false;
    private boolean finishable = false;
    private GoodsDetail.DataBean goodsDetail = null;
    private int sdkAppId = 1400297482;

    public boolean isRetryable() {
        return retryable;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        Fresco.initialize(this);
        initSelectPhoto();
        //bugly
        CrashReport.initCrashReport(getApplicationContext(), "93185f729f", true);
        //liteorm
        if (liteOrm == null) {
            DataBaseConfig dataBaseConfig = new DataBaseConfig(this, "ysshg.db");
            dataBaseConfig.dbVersion = 1;
            dataBaseConfig.onUpdateListener = null;
            liteOrm = LiteOrm.newSingleInstance(dataBaseConfig);
        }
        liteOrm.setDebugged(true);

//        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
//            @Override
//            public void accept(Throwable throwable) {
//                //异常处理
//                ToastUtil.show("网络异常,请检查您的网络");
//            }
//        });

        initImSdk();
    }

    private void initImSdk() {
        //初始化 IM SDK 基本配置
//判断是否是在主线程
        if (SessionWrapper.isMainProcess(getApplicationContext())) {
            TIMSdkConfig config = new TIMSdkConfig(sdkAppId)
                    .enableCrashReport(false)  //接口已废弃
                    .enableLogPrint(true)
                    .setLogLevel(TIMLogLevel.DEBUG)
                    .setLogPath(Environment.getExternalStorageDirectory().getPath() + "/justfortest/");

            //初始化 SDK
            TIMManager.getInstance().init(getApplicationContext(), config);
        }
        initImUserConfig();
    }

    private void initImUserConfig() {
        //基本用户配置
        TIMUserConfig userConfig = new TIMUserConfig()
                //设置用户状态变更事件监听器
                .setUserStatusListener(new TIMUserStatusListener() {
                    @Override
                    public void onForceOffline() {
                        //被其他终端踢下线
                        Log.i(tag, "onForceOffline");
                    }

                    @Override
                    public void onUserSigExpired() {
                        //用户签名过期了，需要刷新 userSig 重新登录 IM SDK
                        Log.i(tag, "onUserSigExpired");
                    }
                })
                //设置连接状态事件监听器
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                        Log.i(tag, "onConnected");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        Log.i(tag, "onDisconnected");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        Log.i(tag, "onWifiNeedAuth");
                    }
                })
                //设置群组事件监听器
                .setGroupEventListener(new TIMGroupEventListener() {
                    @Override
                    public void onGroupTipsEvent(TIMGroupTipsElem elem) {
                        Log.i(tag, "onGroupTipsEvent, type: " + elem.getTipsType());
                    }
                })
                //设置会话刷新监听器
                .setRefreshListener(new TIMRefreshListener() {
                    @Override
                    public void onRefresh() {
                        Log.i(tag, "onRefresh");
                    }

                    @Override
                    public void onRefreshConversation(List<TIMConversation> conversations) {
                        Log.i(tag, "onRefreshConversation, conversation size: " + conversations.size());
                    }
                });

//将用户配置与通讯管理器进行绑定
        TIMManager.getInstance().setUserConfig(userConfig);

        TIMManager.getInstance().addMessageListener(new TIMMessageListener() {
            @Override
            public boolean onNewMessages(List<TIMMessage> list) {
                Toast.makeText(mainActivity, "收到新的客服消息", Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }

    private void initSelectPhoto() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImgLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    public static BaseApplication getInstance() {
        return app;
    }

    public static LiteOrm getLiteOrm() {
        return liteOrm;
    }

    public MainActivity getMainActivity() {
        return mainActivity;
    }

    public void setMainActivity(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
    }

    public void regToWeiXin() {
        wxapi = WXAPIFactory.createWXAPI(this, appID, true);
        wxapi.registerApp(appID);
    }

    public boolean isFinishable() {
        return finishable;
    }

    public IWXAPI getWxapi() {
        if (null != wxapi) {
            return wxapi;
        } else {
            regToWeiXin();
            return wxapi;
        }
    }

    public void setRetryable(boolean b) {
        this.retryable = b;
    }

    public void setFinishable(boolean b) {
        this.finishable = b;
    }

    public void setCurrentGoodDetail(GoodsDetail.DataBean goodsDetailData) {
        this.goodsDetail = goodsDetailData;
    }

    public GoodsDetail.DataBean getCurrentGoodsDetail() {
        if (goodsDetail != null) {
            return goodsDetail;
        } else {
            return null;
        }
    }
}
